//作用：需要将所有的DOM元素对象以及相关的资源全部都加载完毕之后，再来实现的事件函数
window.onload = function () {
    // 声明一个记录点击的缩略图下标
    var bigimgIndex = 0;


    navPathDataBind();
    bigClassBind();
    thumbnailData();
    thumbnailClick();
    thumbnailLeftRightClick();
    rightTopData();
    rightBottomData();
    clickedBind();
    chooseprice();
    leftTab();
    rightTab();
    rightAsideBind();


    //路径导航的数据渲染
    navPathDataBind();
    function navPathDataBind() {
        /**
         * 思路：
         * 1. 先获取路径导航的页面元素（navPath）
         * 2. 再来获取所需要的数据（data.js -> goodData.path）
         * 3. 由于数据是需要动态产生的，那么相应的dom元素也应该是动态产生的，
         * 含义是需要根据数据的数量来进行创建DOM元素
         * 4. 在遍历数据创建DOM元素的最后一条，只创建a标签，而不创建i标签
         */
        //1 获取路径导航的页面元素（navPath）
        var navPath = document.querySelector('#wrapper #content .contentMain #navPath');
        //2 获取所需要的数据
        var path = goodData.path;
        //3 遍历数据
        for (let i = 0; i < path.length; i++) {
            if (i == path.length - 1) {
                //只需要创建a而且没有href属性
                var aNode = document.createElement("a");
                aNode.innerHTML = path[i].title;
                navPath.appendChild(aNode);

            } else {
                //4 创建a标签
                var aNode = document.createElement("a");
                aNode.href = path[i].url;
                aNode.innerHTML = path[i].title;
                //5 创建i标签
                var iNode = document.createElement("i");
                iNode.innerHTML = "/";
                //6 让navPath元素追加a和i
                navPath.appendChild(aNode);
                navPath.appendChild(iNode);
            }
        }
    }

    //放大镜的移入，移出效果
    function bigClassBind() {
        /**
         * 思路：
         * 1 获取小图框元素对象，并且设置移入事件（onmouseenter）
         * 2 动态创建蒙版元素以及大图框和大图片元素
         * 3 移出时(onmouseleave)需要移除蒙版元素和大图框
         */
        // 1 获取小图框元素对象
        var smallPic = document.querySelector('#wrapper #content .contentMain #center #left #leftTop #smallPic');
        //获取leftTop元素
        var leftTop = document.querySelector('#wrapper #content .contentMain #center #left #leftTop');


        //获取数据
        var imagessrc = goodData.imagessrc;

        //2 设置移入事件
        smallPic.onmouseenter = function () {
            //3 创建蒙版元素
            var maskDiv = document.createElement('div');
            maskDiv.className = "mask";

            //4 创建大图框元素
            var BigPic = document.createElement('div');
            BigPic.id = 'bigPic';

            //5 创建大图片元素
            var BigImg = document.createElement('img');
            BigImg.src = imagessrc[bigimgIndex].b;

            //6 大图框追加大图片
            BigPic.appendChild(BigImg);

            //7 小图框追加蒙版元素
            smallPic.appendChild(maskDiv)

            //8 leftTop元素追加大图框
            leftTop.appendChild(BigPic);

            //设置移动事件
            smallPic.onmousemove = function (event) {
                var left = event.clientX - smallPic.getBoundingClientRect().left - maskDiv.offsetWidth / 2;
                var top = event.clientY - smallPic.getBoundingClientRect().top - maskDiv.offsetHeight / 2;

                if (left < 0) {
                    left = 0;
                } else if (left > smallPic.clientWidth - maskDiv.offsetWidth + 1) {
                    left = smallPic.clientWidth - maskDiv.offsetWidth + 1;
                }

                if (top < 0) {
                    top = 0;
                } else if (top > smallPic.clientHeight - maskDiv.offsetHeight + 1) {
                    top = smallPic.clientHeight - maskDiv.offsetHeight + 1;
                }


                //设置left和top属性
                maskDiv.style.left = left + "px";
                maskDiv.style.top = top + "px";

                //移动的比例关系 = 蒙版元素移动的距离 / 大图片元素移动的距离
                // 蒙版元素移动的距离 = 小图框宽度 - 蒙版元素的宽度
                // 大图片元素移动的距离 = 大图片宽度 - 大图框元素的宽度
                var scale = (smallPic.clientWidth - maskDiv.offsetWidth) / (BigImg.offsetWidth - BigPic.clientWidth)
                //求大图片元素移动的距离
                BigImg.style.left = -left / scale + 'px';
                BigImg.style.top = -top / scale + 'px';
            }



            //设置移出事件
            smallPic.onmouseleave = function () {
                //让小图框移除蒙版元素
                smallPic.removeChild(maskDiv);
                //leftTop元素移除大图框
                leftTop.removeChild(BigPic);
            }

        }



    }


    //动态渲染放大镜缩略图的数据
    function thumbnailData() {
        var ul = document.querySelector('#wrapper #content .contentMain #center #left #leftBottom #piclist ul');
        var imagessrc = goodData.imagessrc;
        for (let i = 0; i < imagessrc.length; i++) {
            var newLi = document.createElement('li');
            let newImg = document.createElement('img');
            newImg.src = imagessrc[i].s;
            newLi.appendChild(newImg);
            ul.appendChild(newLi);

        }



    }

    //点击缩略图的效果
    function thumbnailClick() {
        let liNodes = document.querySelectorAll('#wrapper #content .contentMain #center #left #leftBottom #piclist ul li');
        let smallPic_img = document.querySelector('#wrapper #content .contentMain #center #left #leftTop #smallPic img');
        let imagessrc = goodData.imagessrc;
        //小图路径需要默认和imagessrc的第一个元素小图的路径是一致的
        smallPic_img.src = imagessrc[0].s;
        for (let i = 0; i < liNodes.length; i++) {
            liNodes[i].onclick = function () {
                bigimgIndex = i;
                //变换小图路径
                smallPic_img.src = imagessrc[i].s;

            }
        }



    }

    //点击缩略图左右箭头的效果
    function thumbnailLeftRightClick() {
        /**
         * 思路：
         * 1 先获取左右两端的箭头按钮
         * 2 再获取可视的div以及ul元素和所有的li元素
         * 3 计算（发生起点、步长、总体运动的距离值）
         * 4 然后再发生点击事件
         */
        let prev = document.querySelector('#wrapper #content .contentMain #center #left #leftBottom a.prev');
        let next = document.querySelector('#wrapper #content .contentMain #center #left #leftBottom a.next');

        let ul = document.querySelector('#wrapper #content .contentMain #center #left #leftBottom #piclist ul');
        let liNodes = document.querySelectorAll('#wrapper #content .contentMain #center #left #leftBottom #piclist ul li');

        //计算
        let start = 0;
        let step = (liNodes[0].offsetWidth + 20) * 2;
        let endPosition = (liNodes.length - 5) * (liNodes[0].offsetWidth + 20);

        //发生事件
        prev.onclick = function () {
            start -= step;
            if (start < 0) {
                start = 0;
            }
            ul.style.left = -start + 'px';
        }

        next.onclick = function () {
            start += step;
            if (start > endPosition) {
                start = endPosition;
            }
            ul.style.left = -start + 'px';
        }

    }

    //商品详情数据的动态渲染
    function rightTopData() {
        let rightTop = document.querySelector('#wrapper #content .contentMain #center #right .rightTop');
        let goodsDetail = goodData.goodsDetail;
        var s = `<h3>${goodsDetail.title}</h3>
                <p>${goodsDetail.recommend}</p>
                <div class="priceWrap">
                    <div class="priceTop">
                        <span>价&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;格</span>
                        <div class="price">
                            <span>￥</span>
                            <p>${goodsDetail.price}</p>
                            <i>降价通知</i>
                        </div>
                        <p>
                            <span>累计评价</span>
                            <span>${goodsDetail.evaluateNum}</span>
                        </p>

                    </div>
                    <div class="priceBottom">
                        <span>促&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;销</span>
                        <p>
                            <span>${goodsDetail.promoteSales.type}</span>
                            <span>${goodsDetail.promoteSales.content}</span>
                        </p>

                    </div>
                </div>
                <div class="support">
                    <span>支&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;持</span>
                    <p>${goodsDetail.support}</p>
                </div>
                <div class="address">
                    <span>配&nbsp;送&nbsp;至</span>
                    <p>${goodsDetail.address}</p>
                </div>`
            //重新渲染rightTop元素
            rightTop.innerHTML = s;


    }


    //商品参数数据的动态渲染
    function rightBottomData() {
        let chooseWrap = document.querySelector('#wrapper #content .contentMain #center #right .rightBottom .chooseWrap');
        let crumbData = goodData.goodsDetail.crumbData;

        for(let i=0; i<crumbData.length; i++){

            let dlNode = document.createElement('dl');

            let dtNode = document.createElement('dt');
            dtNode.innerText = crumbData[i].title;
            dlNode.appendChild(dtNode);

            for(let j=0; j<crumbData[i].data.length; j++){
                let ddNode = document.createElement('dd');
                ddNode.innerText = crumbData[i].data[j].type;
                ddNode.setAttribute('price', crumbData[i].data[j].changePrice);

                dlNode.appendChild(ddNode);
            }

            chooseWrap.appendChild(dlNode);

        }

    }

    //点击商品参数之后的颜色排他效果
    function clickedBind() {

        let dlNodes = document.querySelectorAll('#wrapper #content .contentMain #center #right .rightBottom .chooseWrap dl');
        
        let arr = new Array(dlNodes.length);

        let chooseDiv = document.querySelector('#wrapper #content .contentMain #center #right .rightBottom .choose');

        arr.fill(0);

        for(let i=0;i<dlNodes.length;i++){
            let ddNodes = dlNodes[i].querySelectorAll('dd');
            for(let j=0;j<ddNodes.length;j++){
                ddNodes[j].onclick = function(){
                    //清空choose元素
                    chooseDiv.innerHTML = '';

                    for(let k=0;k<ddNodes.length;k++){
                        ddNodes[k].style.color = '#666';
                    }
                    this.style.color = 'red';

                    //点击哪一个dd元素动态的产生一个新的mark标记元素
                    arr[i] = this;

                    changePriceBind(arr);

                    arr.forEach(function (value, index) {
                        if(value){
                            let markDiv = document.createElement('div');
                            markDiv.className = 'mark';
                            markDiv.innerText = value.innerText;

                            let aNode = document.createElement('a');
                            aNode.innerText = 'X';
                            aNode.setAttribute('index', index);
                            markDiv.appendChild(aNode);
                            chooseDiv.appendChild(markDiv);
                        }
                    })

                    //获取所有的a标签元素，并且循环发生点击事件
                    let aNodes = document.querySelectorAll('#wrapper #content .contentMain #center #right .rightBottom .choose .mark a');

                    for(let n=0;n<aNodes.length;n++){
                        aNodes[n].onclick = function(){
                            let idx = this.getAttribute('index');
                            arr[idx] = 0;
                            let ddlist = dlNodes[idx].querySelectorAll('dd');
                            for(let m=0;m<ddlist.length;m++){
                                ddlist[m].style.color = '#666';
                            }
                            ddlist[0].style.color = 'red';
                            chooseDiv.removeChild(this.parentNode);

                            changePriceBind(arr);
                        }
                    }
                }
            }
        }
    }

    //价格变动的函数声明，这个函数是需要在点击dd的时候以及删除mark标记的时候才需要调用
    function changePriceBind(arr){
        let oldprice = document.querySelector('#wrapper #content .contentMain #center #right .rightTop .priceWrap .priceTop .price p');

        let price = goodData.goodsDetail.price;

        for(let i=0;i<arr.length;i++){
            if(arr[i]){
                let changeprice = Number(arr[i].getAttribute('price'));
                price += changeprice;
            }
        }
        oldprice.innerText = price;

        //将变化后的价格写入到下方左侧标签中
        let leftprice = document.querySelector('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .chooseBox .listWrap .left p');
        leftprice.innerText = '￥' + price;
        
        let ipts = document.querySelectorAll('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .chooseBox .listWrap .middle li input');
        let newprice = document.querySelector('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .chooseBox .listWrap .right i');

        for(let i=0;i<ipts.length;i++){
            if(ipts[i].checked){
                price += Number(ipts[i].value);
            }
        }
        newprice.innerText = '￥' + price;





    }


    //选择搭配中间区域复选框选中套餐价变动效果
    function chooseprice(){
        let ipts = document.querySelectorAll('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .chooseBox .listWrap .middle li input');
        let leftprice = document.querySelector('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .chooseBox .listWrap .left p');
        let newprice = document.querySelector('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .chooseBox .listWrap .right i');
        for(let i=0;i<ipts.length;i++){
            ipts[i].onclick = function(){
                let oldprice = Number(leftprice.innerText.slice(1));
                for(let j=0;j<ipts.length;j++){
                    if(ipts[j].checked){
                        oldprice = oldprice + Number(ipts[j].value);
                    }
                }
                //重新写会到套餐价中
                newprice.innerText = '￥' + oldprice;
            }


        }
    }


    //封装一个公共的选项卡函数
    function Tab(tabBtns, tabConts) {
        for(let i=0;i<tabBtns.length;i++){
            tabBtns[i].onclick = function(){
                for(let j=0;j<tabBtns.length;j++){
                    tabBtns[j].className = '';
                    tabConts[j].className = '';
                }
                this.className = 'active';
                tabConts[i].className = 'active';
            }
        }
    }

    //点击左侧选项卡
    function leftTab(){
        let h4s = document.querySelectorAll('#wrapper #content .contentMain .goodsDetailWrap .leftAside .asideTop h4');
        let divs = document.querySelectorAll('#wrapper #content .contentMain .goodsDetailWrap .leftAside .asideContent>div');
        Tab(h4s, divs);

    }

    //点击右侧选项卡
    function rightTab(){
        let lis = document.querySelectorAll('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .BottomDetail .tabBtns li');
        let divs = document.querySelectorAll('#wrapper #content .contentMain .goodsDetailWrap .rightDetail .BottomDetail .tabContents div');

        Tab(lis, divs);
    }


    //右边侧边栏的点击效果
    function rightAsideBind(){
        let btns = document.querySelector('#wrapper .rightAside .btns');
        let rightAside = document.querySelector('#wrapper .rightAside');
        
        let flag = true; //关闭状态
        btns.onclick = function () {
            if(flag){
                btns.className = 'btns btnsOpen';
                rightAside.className = 'rightAside asideOpen';
            }else{
                btns.className = 'btns btnsClose';
                rightAside.className = 'rightAside asideClose';
            }
            flag = !flag;
        }
    }

















}